import React, { useState, useEffect, useMemo, useRef } from 'react';
import {
    Drawer,
    Icon,
    Input,
    Radio,
    Button,
    Tabs,
    Checkbox,
    Row,
    Col,
    Modal,
    message,
    Select,
    Divider,
    Typography,
    Switch
} from 'antd';
import _ from 'lodash';
import { connect } from 'umi';
import { useOnClickOutside } from '../../../hooks';
import { NodeUtils } from '../FlowCard/util.js';
import { RadioForm } from '../../ScopeGroup';
import { RenderConditionForm, Organization, OrgListSelect } from '../components';
import { FormAuth } from './components';
import styles from './styles.less';

const { TabPane } = Tabs;
const { Option } = Select;
const { Text } = Typography;

const PropPanel = ({ data, value, onConfirm, onCancel, workFlowModel, dispatch }) => {
    const { basicData, processConditions, formItemList } = workFlowModel;
    const { organizationCode } = basicData;

    const [scopeGroup, setScopeGroup] = useState(basicData.scopeGroup); // 开始节点发起人，同步的是model的数据
    const [visible, setVisible] = useState(false); // 控制面板显隐
    const [titleInputVisible, setTitleInputVisible] = useState(false); //  是否显示标题输入框  startNode 不显示
    const [properties, setProperties] = useState(null); // 当前节点数据

    const [showingPCons, setShowingPCons] = useState([]); // 用户选择了得条件  被选中的才会被展示在面板上编辑
    const [dialogVisible, setDialogVisible] = useState(false); // 控制流程条件选项Dialog显隐
    const [conditionCheckGroupOption, setConditionCheckGroupOption] = useState([]); // 选择条件 check group options
    const [conditionData, setConditionData] = useState(null); // 条件节点条件数据
    const [priorityLength, setPriorityLength] = useState(0); // 当为条件节点时  显示节点优先级选项的数据
    const [processConditionsArr, setProcessConditionsArr] = useState([]); // 作为条件的数组，包含套件的条件

    const [approverForm, setApproverForm] = useState({
        formOperates: [], // 表单操作权限集合
        counterSign: true // 是否为会签
    });

    const orgRef = useRef(null);

    // 顶部标题组件事件
    const titleRef = useRef();
    useOnClickOutside(titleRef, () => setTitleInputVisible(false));

    const [startForm, setStartForm] = useState({
        formOperates: []
    });

    // 未使用的条件个数
    const notUseConNum = useMemo(
        () =>
            // 发起人是默认就有 所以需要加 1
            processConditionsArr.length - showingPCons.length + 1,
        [processConditionsArr, showingPCons]
    );

    // 判断是否是条件节点
    const isConditionNode = () => (value ? NodeUtils.isConditionNode(value) : false);

    /** 判断是否是审批节点 */
    const isApproverNode = () => (value ? NodeUtils.isApproverNode(value) : false);

    const isStartNode = () => (value ? NodeUtils.isStartNode(value) : false);

    const isCopyNode = () => (value ? NodeUtils.isCopyNode(value) : false);

    const getFormOperates = () => {
        let res = [];
        if (isApproverNode()) {
            res = approverForm.formOperates;
        }
        if (isStartNode()) {
            res = startForm.formOperates;
        }
        return res;
    };

    // 更改表单权限
    const changeFormOperate = (val, id = null) => {
        const { formOperates } = isStartNode() ? startForm : approverForm;
        const arr = formOperates.map(t => {
            const temp = t;
            if (!id) {
                // 对作为条件的组件进行特殊处理
                const usedArr = processConditionsArr.filter(item => item.isUsed);
                if (usedArr.findIndex(item => item.formId === temp.formId) > -1) {
                    if (isStartNode() && val === 2) {
                        temp.formOperate = val;
                    } else if (isApproverNode() && val !== 2) {
                        temp.formOperate = val;
                    }
                } else {
                    temp.formOperate = val;
                }
            } else if (t.formId === id) {
                temp.formOperate = val;
            }
            return temp;
        });
        if (isStartNode()) {
            setStartForm({ ...startForm, formOperates: arr });
        } else {
            setApproverForm({ ...approverForm, formOperates: arr });
        }
    };

    const initFormOperates = target => {
        const formOperates = (target.properties && target.properties.formOperates) || [];
        const res = [];
        const defaultType = isApproverNode() ? 1 : 2; // 操作权限 0 隐藏 1 只读 2 可编辑
        const getPermissionById = id => {
            const permission = formOperates.find(t => t.formId === id);

            // 对作为条件的组件进行特殊处理
            const usedArr = processConditionsArr.filter(item => item.isUsed);
            if (permission && usedArr.findIndex(item => item.formId === id) > -1) {
                let v = permission.formOperate;
                if (isStartNode() && v !== 2) {
                    v = 2;
                } else if (isApproverNode() && v === 2) {
                    v = 1;
                }
                return v;
            }
            return permission !== undefined ? permission.formOperate : defaultType;
        };
        const format = (list, parentName = '') => {
            const isTitle = v => v === 'Title';
            const isLink = v => v === 'Link';
            list.forEach(t => {
                let labelText = t.label;
                if (isTitle(t.tag)) {
                    labelText = t.titleValue;
                } else if (isLink(t.tag)) {
                    labelText = t.linkText;
                }
                const obj = {
                    formId: t.formId,
                    label: parentName ? [parentName, labelText].join(' - ') : labelText,
                    formOperate: getPermissionById(t.formId)
                };
                if (Array.isArray(t.children)) {
                    format(t.children, t.label);
                } else if (t?.inFormAuth !== false) {
                    // 排除inFormAuth为false的组件
                    res.push(obj);
                }
            });
        };

        const formItems = formItemList;

        format(formItems);
        return res;
    };

    // 开始节点初始化
    const initStartNodeData = () => {
        setStartForm({ ...startForm, formOperates: initFormOperates(value) });
    };

    /**
     * 开始节点确认保存
     */
    const startNodeComfirm = () => {
        // 将发起人组件转换成回显内容
        let content = null;
        const { scopeField, scopeValue, scopeLabel } = scopeGroup;
        content = scopeLabel.join('，');

        if (scopeField === 'company') {
            content = '全体员工';
        } else if (scopeField !== 'company' && scopeValue.length === 0) {
            message.error('请选择发起人');
            return false;
        }

        const formOperates = startForm.formOperates.map(t => ({
            formId: t.formId,
            formOperate: t.formOperate
        }));

        const tempProperties = {};
        Object.assign(tempProperties, properties, { formOperates });

        // 同步基础设置发起审批人
        dispatch({ type: 'workFlowModel/basicDataSave', payload: { scopeGroup } });

        if (onConfirm) {
            onConfirm(tempProperties, content);
        }

        setVisible(false);
        return null;
    };

    /**
     * 审批节点确认保存
     */
    const approverNodeComfirm = () => {
        if (
            !approverForm.assigneeType ||
            (approverForm.candidateUsers && approverForm.candidateUsers.includes('*')) ||
            (approverForm.url && approverForm.url !== '' && approverForm.approvers.length === 0)
        ) {
            message.error('请选择审批人');
            return false;
        }
        const formOperates = approverForm.formOperates.map(t => ({
            formId: t.formId,
            formOperate: t.formOperate
        }));
        const tempProperties = {};
        delete approverForm.title;
        Object.assign(tempProperties, properties, approverForm, { formOperates });
        delete tempProperties.url;

        const content = approverForm.content || '请设置审批人';
        if (onConfirm) {
            onConfirm(tempProperties, content);
        }
        setVisible(false);
        return null;
    };

    /**
     * 初始化审批节点所需数据
     */
    const initApproverNodeData = () => {
        setApproverForm({ sequential: 0, ...approverForm, ...value.properties, formOperates: initFormOperates(value) });
    };

    /**
     * 条件节点确认保存得回调
     */
    const conditionNodeComfirm = () => {
        const nodeContent = [];
        if (conditionData?.length > 0) {
            conditionData.forEach(item => {
                nodeContent.push(item.labelText);
            });
        }
        // console.log('====>conditionData', conditionData);

        const tempProperties = {};
        Object.assign(tempProperties, properties, { conditions: conditionData || [] });

        if (onConfirm) {
            onConfirm(tempProperties, nodeContent.length > 0 ? nodeContent : '请设置条件');
        }
        setVisible(false);
    };

    /**
     * 初始化条件节点数据
     */
    const initConditionNodeData = () => {
        const nodeConditions = value.properties ? value.properties.conditions : [];
        console.log('== =>processConditions', processConditions);

        if (Array.isArray(processConditionsArr)) {
            const showingPConsArray = [];
            const checkGroupOption = [{ label: '发起人', value: 'initiatorCondition' }];

            // modal的全部条件类型
            processConditionsArr.forEach(item => {
                checkGroupOption.push({ label: item.label, value: item.formId });
            });
            // 判断如果节点已经存在条件就按里面的显示
            if (_.size(nodeConditions) > 0) {
                if (Array.isArray(nodeConditions)) {
                    nodeConditions.forEach(item => {
                        showingPConsArray.push(item.formId);
                    });
                }
            } else {
                checkGroupOption.forEach(item => {
                    showingPConsArray.push(item.value);
                });
            }
            setConditionCheckGroupOption(checkGroupOption);
            setShowingPCons(showingPConsArray);
        }
    };

    /**
     * 删除流程条件
     */
    const onDelCondition = id => {
        const index = showingPCons.findIndex(x => x === id);
        if (index > -1) {
            const arr = _.cloneDeep(showingPCons);
            arr.splice(index, 1);
            setShowingPCons(arr);

            // 条件为空
            if (arr.length === 0) {
                setShowingPCons([]);
            }
        }
    };

    // 初始化抄送节点
    const initCopyNode = () => {
        setProperties(_.cloneDeep(value.properties));
    };

    // 抄送节点回调
    const copyNodeConfirm = () => {
        const content = _.size(properties.labelText) > 0 ? properties.labelText : '请选择抄送人';
        if (onConfirm) {
            onConfirm(properties, content);
        }

        setVisible(false);
    };

    // 确认修改
    const confirm = () => {
        if (isCopyNode()) {
            copyNodeConfirm();
        } else if (isStartNode()) {
            startNodeComfirm();
        } else if (isApproverNode()) {
            approverNodeComfirm();
        } else if (isConditionNode()) {
            conditionNodeComfirm();
        }
    };

    // 关闭抽屉
    const cancel = () => {
        setTimeout(() => {
            if (onCancel) {
                onCancel();
            }
            setVisible(false);
        }, 0);
    };

    // 监听value
    useEffect(() => {
        if (value && value.properties) {
            setVisible(true);
            setProperties(_.cloneDeep(value.properties));

            // 条件节点条件个数
            if (isConditionNode()) {
                const prevNode = NodeUtils.getPreviousNode(value.prevId, data);
                if (prevNode && prevNode.conditionNodes) {
                    setPriorityLength(prevNode.conditionNodes.length);
                }
            }
        }
    }, [value]);

    useEffect(() => {
        if (!visible) return;

        if (isCopyNode()) {
            initCopyNode();
        } else if (isStartNode()) {
            initStartNodeData();
        } else if (isApproverNode()) {
            initApproverNodeData();
        } else if (isConditionNode()) {
            initConditionNodeData();
        }
    }, [visible]);

    useEffect(() => {
        if (processConditions && processConditions.length > 0) {
            const arr = [];
            processConditions.forEach(item => {
                if (item.cmpType === 'custom') {
                    item.children.forEach(subItem => {
                        if (subItem.proCondition) {
                            arr.push({
                                ...subItem,
                                parentFormId: item.formId
                            });
                        }
                    });
                } else {
                    arr.push(item);
                }
            });
            setProcessConditionsArr(arr);
        }
    }, [processConditions]);

    return (
        properties && (
            <Drawer
                width={550}
                zIndex={999}
                className={styles.drawer}
                visible={visible}
                closable={false}
                onClose={cancel}
            >
                {/* 标题 */}
                {value && value.type === 'start' && properties.title ? (
                    <header className={styles.header}>{properties.title}</header>
                ) : (
                    <header className={styles.header}>
                        <Row gutter={16}>
                            <Col span={isConditionNode() ? 11 : 24}>
                                <span ref={titleRef}>
                                    {!titleInputVisible && (
                                        <span
                                            onClick={() => {
                                                setTitleInputVisible(true);
                                            }}
                                            style={{ cursor: 'pointer' }}
                                        >
                                            {properties.title}
                                            <Icon type="edit" />
                                        </span>
                                    )}
                                    {titleInputVisible && (
                                        <Input
                                            defaultValue={properties.title}
                                            style={{ zIndex: 9 }}
                                            onChange={e => {
                                                setProperties({ ...properties, title: e.target.value });
                                            }}
                                        />
                                    )}
                                </span>
                            </Col>
                            {isConditionNode() && (
                                <>
                                    <Col span={7}>
                                        默认条件：
                                        <Switch
                                            defaultChecked={properties.isDefault}
                                            onChange={v => {
                                                setProperties({ ...properties, isDefault: v });
                                            }}
                                        />
                                    </Col>
                                    <Col span={6}>
                                        <Select
                                            style={{ width: '100px' }}
                                            defaultValue={properties.priority}
                                            onChange={e => {
                                                setProperties({ ...properties, priority: e });
                                            }}
                                        >
                                            {Array.from(Array(priorityLength), (v, i) => i).map(item => (
                                                <Option key={item} value={item}>
                                                    优先级{item + 1}
                                                </Option>
                                            ))}
                                        </Select>
                                    </Col>
                                </>
                            )}
                        </Row>
                    </header>
                )}

                {/* 条件 */}
                {value && isConditionNode() && (
                    <section className={styles.conditionPane}>
                        {properties.isDefault === true ? (
                            '默认条件不需要添加条件'
                        ) : (
                            <>
                                <RenderConditionForm
                                    data={processConditionsArr}
                                    onDelete={onDelCondition}
                                    showingPCons={showingPCons}
                                    conditionData={value.properties.conditions}
                                    setConditionData={setConditionData}
                                    organizationCode={organizationCode}
                                />
                                <div style={{ paddingLeft: 10, marginTop: '1em' }}>
                                    <Button
                                        type="primary"
                                        icon="plus"
                                        onClick={() => {
                                            setDialogVisible(true);
                                        }}
                                    >
                                        添加条件
                                    </Button>
                                    <span style={{ color: '#aaa', marginLeft: 16, fontSize: 12 }}>
                                        还有{notUseConNum}个可用条件
                                    </span>
                                </div>
                            </>
                        )}
                    </section>
                )}

                {/* 审批人 */}
                {value && (isApproverNode() || isStartNode()) && (
                    <section className={styles.approverPane}>
                        <Tabs defaultActiveKey="config" animated={false} style={{ height: '100%' }}>
                            <TabPane tab={`设置${value.type === 'approver' ? '审批人' : '发起人'}`} key="config">
                                {/* 开始节点 */}
                                {value.type === 'start' ? (
                                    <Row style={{ padding: 10, height: '100%' }}>
                                        <Col span={24} className={styles.paneTitle}>
                                            发起人
                                        </Col>
                                        <Col span={24}>
                                            <div style={{ paddingBottom: '100px' }}>
                                                <RadioForm
                                                    value={scopeGroup}
                                                    organizationCode={organizationCode}
                                                    onChange={e => {
                                                        setScopeGroup(e);
                                                        dispatch({
                                                            type: 'workFlowModel/basicDataSave',
                                                            payload: {
                                                                scopeGroup: e
                                                            }
                                                        });
                                                    }}
                                                />
                                            </div>
                                        </Col>
                                    </Row>
                                ) : (
                                    value.type === 'approver' && (
                                        <div>
                                            <Text type="secondary" className={styles.paneTitle}>
                                                最多选择20个审批人
                                            </Text>
                                            <div style={{ padding: 12 }}>
                                                <Organization
                                                    defaultValue={approverForm.approvers}
                                                    defaultType={approverForm.assigneeType}
                                                    organizationCode={organizationCode}
                                                    bData={approverForm}
                                                    showTreeFlag={approverForm.showTreeFlag}
                                                    onChange={e => {
                                                        const {
                                                            orgType,
                                                            orgValue,
                                                            orgLabel,
                                                            optionalType,
                                                            candidateUsers,
                                                            url,
                                                            typeText,
                                                            showTreeFlag
                                                        } = e;
                                                        // 节点数据
                                                        setApproverForm({
                                                            ...approverForm,
                                                            content:
                                                                typeText ===
                                                                (Array.isArray(orgLabel) ? orgLabel[0] : orgLabel)
                                                                    ? orgLabel
                                                                    : `【${typeText}：${orgLabel}】`,
                                                            candidateUsers,
                                                            assigneeType: orgType,
                                                            approvers: orgValue,
                                                            url,
                                                            showTreeFlag,
                                                            optionalType
                                                        });
                                                    }}
                                                />
                                            </div>
                                            <Divider style={{ margin: '0 auto 16px' }} />
                                            <p style={{ marginBottom: 16 }} className={styles.paneTitle}>
                                                多人审批时采用的审批方式
                                            </p>
                                            <Radio.Group
                                                onChange={e => {
                                                    setApproverForm({ ...approverForm, sequential: e.target.value });
                                                }}
                                                defaultValue={approverForm.sequential || 0}
                                            >
                                                <Radio value={1} style={{ display: 'block', marginBottom: 10 }}>
                                                    会签（须所有审批人同意）
                                                </Radio>
                                                <Radio value={0} style={{ display: 'block', marginBottom: 10 }}>
                                                    或签（一名审批人同意或拒绝即可）
                                                </Radio>
                                            </Radio.Group>
                                        </div>
                                    )
                                )}
                            </TabPane>

                            <TabPane tab="表单权限" key="formAuth">
                                <FormAuth
                                    data={getFormOperates()}
                                    onChange={changeFormOperate}
                                    processConditions={processConditionsArr}
                                    activeData={value}
                                />
                            </TabPane>
                        </Tabs>
                    </section>
                )}

                {value && isCopyNode() && (
                    <section className={styles.copyPane}>
                        <div style={{ marginBottom: 16 }} className={styles.paneTitle}>
                            请选择抄送人
                        </div>
                        <OrgListSelect
                            defaultValue={properties.backData}
                            organizationCode={organizationCode}
                            ref={orgRef}
                            type="3"
                            onChange={e => {
                                const initatorObj = e;
                                const obj = {
                                    labelText: '',
                                    backData: initatorObj,
                                    copyUsers: []
                                };
                                if (_.size(initatorObj) > 0) {
                                    let isEmptyData = true;
                                    Object.keys(initatorObj).forEach(item => {
                                        let tempValue = initatorObj[item].value;
                                        console.log(
                                            '===============================================>tempValue',
                                            tempValue
                                        );

                                        if (!tempValue) {
                                            // 值为空的时候删除相对应的回填数据
                                            delete obj.backData[item];
                                            return;
                                        }

                                        const tempLabel = [];

                                        if (!Array.isArray(tempValue)) {
                                            tempValue = [tempValue];
                                        }
                                        if (_.size(tempValue) > 0) {
                                            tempValue.forEach(subItem => {
                                                tempLabel.push(subItem.label);
                                                obj.copyUsers.push({
                                                    key: initatorObj[item].keyVariable,
                                                    value: subItem.label === '是' ? '' : subItem.key || subItem.value, // 是否类型不传value
                                                    name: subItem.label
                                                });
                                            });
                                            // 显示回填
                                            obj.labelText = `${obj.labelText}【${
                                                initatorObj[item].typeText
                                            }：${tempLabel.join('，')}】\n`;

                                            isEmptyData = false;
                                        }
                                    });
                                    if (isEmptyData) {
                                        // 组件返回值为空，清除数据
                                        Object.assign(obj, {
                                            labelText: '',
                                            backData: {},
                                            copyUsers: []
                                        });
                                    }
                                }
                                setProperties({ ...properties, ...obj });
                            }}
                        />
                    </section>
                )}

                <Modal title="选择条件" visible={dialogVisible} footer={null} onCancel={() => setDialogVisible(false)}>
                    <Checkbox.Group
                        value={showingPCons}
                        options={conditionCheckGroupOption}
                        onChange={checkedValue => {
                            setShowingPCons([...checkedValue]);
                        }}
                    />
                </Modal>

                <div className={styles.actions}>
                    <Button
                        style={{ marginRight: 16 }}
                        onClick={() => {
                            cancel();
                        }}
                    >
                        取消
                    </Button>
                    <Button
                        type="primary"
                        onClick={() => {
                            confirm();
                        }}
                    >
                        确定
                    </Button>
                </div>
            </Drawer>
        )
    );
};

export default connect(({ workFlowModel }) => ({
    workFlowModel
}))(PropPanel);
